<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/11
 * Time: 16:03
 * * @copyright: ©2024 永州微聚商网络科技有限公司
 * @link: https://www.weijuyunke.com
 */


namespace app\admin\controller;

use app\admin\model\OperateLog;
use app\admin\model\StaffRole;
use app\home\model\UserToken;
use app\merchant\model\PayAmount;
use app\merchant\model\Store;
use app\Request;
use app\admin\model\Staff as StaffModel;
use app\services\jwt\JwtService;

class  Staff
{
    public function Login(Request $request)
    {
        $param = $request->param();
        $staffModel = new StaffModel();
        $where = [];
        if (isset($param['username']) && !empty($param['username'])) {
            $where['phone|name'] = $param['username'];
        } else {
            return adminError('请输入账号');
        }
        $staffInfo = $staffModel->where($where)->find();
        if (empty($staffInfo)) {
            return adminError('账号不存在');
        }
        if ($staffInfo) {
            if (md5(md5($param['password']) . $staffInfo['salt']) != $staffInfo['password']) {
                return adminError('密码有误', [], 1);
            }
        }
        $jwt = new JwtService();
        //根据用户id生成token
        $StaffRoleModel = new StaffRole();
        $staffRoleInfo = $StaffRoleModel->where(['staff_id' => $staffInfo['id']])->find();
        $token = $jwt->getMerchantToken($staffInfo['id'], $staffRoleInfo['role_id'],$staffRoleInfo['store_id'],30);  //获取token
        $tokenConfig = ['uid' => $staffInfo['id'], 'token' => $token, 'create_time' => time(),
            'effective_time' => time() + 60 * 60 * 24 * 30, 'login_ip' => $request->ip(), 'type' => 3];  //token配置信息  //token配置信息
        $tokenModel = new UserToken();
        $tokenModel->insert($tokenConfig);  //更新token
        $operateLog = new OperateLog();
        $data = [
            'route' => $request->controller() . '/' . $action = $request->action(),
            'user_type' => 1,
            'operate_id' => $staffInfo['id'],
            'method' => 'post',
            'req_data' => json_encode($param),
            'ip' => $request->ip(),
            'name' => '登录',
            'create_time' => time(),
        ];

        $operateLog->insert($data);
        $user = $staffModel->where(['id' => $staffInfo['id']])
            ->field('id,phone,name,openid,unionid,nickname,create_time')
            ->find();
        $roleModel = new \app\admin\model\Role();
        $roleInfo = $roleModel->where(['id'=>  $staffRoleInfo['role_id']])->find();

        if ($roleInfo){
            $user['role_type'] = $roleInfo['type'];
        }else{
            $user['role_type'] = 1;
        }
        $user['access_token'] = $token;
        return adminSuccess('成功', $user);
    }

    public function addStaff(Request $request)
    {
        $param = $request->param();
        $salt = createNonceStr(4);

        $data = [
            'phone' => $param['phone'],
            'name' => $param['name'],
            'salt' => $salt,
            'password' => md5(md5($param['password']) . $salt),
            'create_time' => time(),
            'real_name' => $param['real_name'],

        ];
        $staffModel = new StaffModel();
        $staffInfo = $staffModel->where(['phone' => $param['phone']])->find();
        if ($staffInfo){
            return adminError('手机号已存在');
        }
        $staffInfo = $staffModel->where(['name' => $param['name']])->find();
        if ($staffInfo){
            return adminError('账号已添加');
        }

        $staffRoleModel  = new StaffRole();


        if ( empty($param['roleIds'])){
            return adminError('请选择用户角色');
        }
        $staffModel->startTrans();
        $staffModel->insert($data);
        $id = $staffModel->getLastInsID();
        $data = [];
        foreach ($param['roleIds'] as $key =>  $value){
            if (empty($value)){
                $staffModel->rollback();
                return adminError('角色不全');
            }
            $data[$key]['staff_id']  = $id;
            $data[$key]['role_id']  =  $value;
            $data[$key]['store_id']  = $param['storeId'][$key];
            $data[$key]['create_time']  = time();
        }

        $staffRoleModel->insertAll($data);
        $staffModel->commit();
        return adminSuccess('添加成功');
    }

    public function user(Request $request)
    {

        $roleModel = new \app\admin\model\Role();
        $roleInfo = $roleModel->where(['id'=>  $request->staff_account['role_id']])->find();
        if ($roleInfo){
            $request->staff_account['role_type'] = $roleInfo['type'];
        }else{
            $request->staff_account['role_type'] = 1;
        }
        $user = $request->staff_account;
        $user['authorities'] = $request->menu;

        return adminSuccess('成功', $user);
    }

    public function userList(Request $request)
    {
        $param = $request->param();
        $staffModel = new \app\admin\model\Staff();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['status', 'in', [1, 2]];
        if (isset($param['phone']) && !empty($param['phone'])) {
            $where[] = ['phone', 'like', '%' . $param['phone'] . '%'];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }
        $staffList = $staffModel->where($where)->limit($start, $limit)->select()->toArray();
        if ($staffList) {
            $staffId = array_column($staffList, 'id');
            $staffRoleModel = new \app\admin\model\StaffRole();
            $staffRoleList = $staffRoleModel->where('staff_id', 'in', $staffId)->select()->toArray();
            $roleId = array_column($staffRoleList, 'role_id');
            $roleModel = new \app\admin\model\Role();
            $roleList = $roleModel->where('id', 'in', $roleId)->select()->toArray();
            $storeId = array_column($staffRoleList, 'store_id');
            $storeModel = new Store();
            $storeList = $storeModel->where('id', 'in', $storeId)->select()->toArray();
            $storeListById  = array_column($storeList,null,'id');
            foreach ($staffRoleList as $staffRoleKey => $staffRoleValue) {
                    foreach ($roleList as $roleValue) {
                    if ($staffRoleValue['role_id'] == $roleValue['id']) {
                        $staffRoleList[$staffRoleKey]['role_name'] = $roleValue['name'];
                        $staffRoleList[$staffRoleKey]['type'] = $roleValue['type'];
                    }
                }
                if (array_key_exists($staffRoleValue['store_id'], $storeListById)) {
                    $staffRoleList[$staffRoleKey]['store_name'] = $storeListById[$staffRoleValue['store_id']]['name'];
                }else{
                    $staffRoleList[$staffRoleKey]['store_name'] = '';
                }

            }
            foreach ($staffList as $staffKey =>  $staffValue){
                foreach ($staffRoleList as $staffRoleKey => $staffRoleValue) {

                    if ($staffValue['id'] == $staffRoleValue['staff_id']){
                        if (  isset($staffList[$staffKey]['role_name'])){
                            $staffList[$staffKey]['roles'][] = $staffRoleValue;
                            $staffList[$staffKey]['role_name'] =  $staffList[$staffKey]['role_name'].','.$staffRoleValue['store_name'].$staffRoleValue['role_name'];
                        }else{
                            $staffList[$staffKey]['role_name'] = $staffRoleValue['store_name'].$staffRoleValue['role_name'];
                            $staffList[$staffKey]['roles'][0] = $staffRoleValue;
                        }

                    }
                }
            }
        }



        $count = $staffModel->where($where)
            ->limit($start, $limit)->select()->count();

        return adminSuccess('用户列表', ['list' => $staffList, 'count' => $count]);
    }

    public function staffUpdate(Request $request){
        $param = $request->param();
        $staffModel = new \app\admin\model\Staff();
        $staffModel->where(['id'=> $param['id']])->update([
            'phone' =>$param['phone'] ,
            'real_name' => $param['phone'],
        ]);
        $staffRoleModel  = new StaffRole();
        $staffRoleModel->where('staff_id','=',$param['id'])->delete();

        if ( empty($param['roleIds'])){
            return adminError('请选择用户角色');
        }
        $data = [];
        foreach ($param['roleIds'] as $key =>  $value){
            $data[$key]['staff_id']  = $param['id'];
            $data[$key]['role_id']  =  $value;
            $data[$key]['store_id']  = $param['storeId'][$key];
            $data[$key]['create_time']  = time();
        }
        $staffRoleModel->insertAll($data);
        return adminSuccess('修改成功');

    }

    public function password(Request $request){
        $param = $request->param();
        $salt  = createNonceStr(4);
        $password =  md5(md5($param['password']) . $salt) ;
        $staffModel = new \app\admin\model\Staff();
        $staffModel->where(['id' => $param['userId']])->update(['password'=> $password,'salt' =>$salt ]);
        return adminSuccess('操作成功');

    }

    public function updateAccount(Request $request){
        $param = $request->param();

        if(isset($param['password'])&& !empty($param['password']) ){
            $salt  = createNonceStr(4);
            $data['password'] = md5(md5($param['password']) . $salt) ;
            $data['salt'] =$salt;
        }
        if(isset($param['phone'])&& !empty($param['phone']) ){

            $data['phone'] =$param['phone'];
        }
        if(isset($param['name'])&& !empty($param['name']) ){

            $data['name'] =$param['name'];
        }
        if(isset($param['real_name'])&& !empty($param['real_name']) ){

            $data['real_name'] =$param['real_name'];
        }

        $staffModel = new \app\admin\model\Staff();
        $staffModel->where(['id' => $request->staff_account['id']])->update($data);
        return adminSuccess('操作成功');

    }


}

